import React, { useEffect, useState } from "react";
import {
  Drawer,
  Card,
  Button,
  Radio,
  Select,
  Input,
  Space,
  Typography,
  Form,
} from "antd";
import { CloseOutlined, SendOutlined } from "@ant-design/icons";

const { Text } = Typography;
const { Option } = Select;

// 自定义标签组件
const Tag = ({
  children,
  color = "default",
}: {
  children: React.ReactNode;
  color?: string;
}) => {
  const colors = {
    green: { bg: "#f6ffed", border: "#b7eb8f", text: "#52c41a" },
    red: { bg: "#fff2f0", border: "#ffccc7", text: "#ff4d4f" },
    blue: { bg: "#e6f7ff", border: "#91d5ff", text: "#1890ff" },
    default: { bg: "#fafafa", border: "#d9d9d9", text: "rgba(0, 0, 0, 0.88)" },
  };

  const style = (colors as any)[color] || colors.default;

  return (
    <span
      style={{
        backgroundColor: style.bg,
        border: `1px solid ${style.border}`,
        color: style.text,
        padding: "1px 8px",
        borderRadius: 4,
        fontSize: 12,
        whiteSpace: "nowrap",
      }}
    >
      {children}
    </span>
  );
};

interface RemoteDebugDrawerProps {
  visible: boolean;
  device: any;
  onClose: () => void;
}

const RemoteDebugDrawer: React.FC<RemoteDebugDrawerProps> = ({
  visible,
  device,
  onClose,
}) => {
  const [form] = Form.useForm();
  const [dataType, setDataType] = useState<string>("hex");
  const [sendMessage, setSendMessage] = useState<string>("");
  const [receiveMessage, setReceiveMessage] = useState<string>("");
  const [isConnected, setIsConnected] = useState<boolean>(false);

  const handleConnection = () => {
    if (isConnected) {
      setIsConnected(false);
      setReceiveMessage("");
      console.log(`断开与设备 ${device.deviceName} 的连接`);
    } else {
      setIsConnected(true);
      console.log(`连接到设备 ${device.deviceName}`);
      // 模拟接收连接成功的消息
      const message = `连接成功\n设备号: ${device.deviceNumber}\n状态: ${device.status}`;
      setReceiveMessage(message);
    }
  };

  const handleSend = () => {
    if (!sendMessage) return;

    // 实际项目中这里会调用API发送消息
    console.log(`发送消息到设备 ${device.deviceName}:`, sendMessage);

    // 模拟接收到的回复
    const response = "命令已接收\n设备状态正常\n序列号:12345";
    setReceiveMessage((prev) => prev + "\n\n---新消息---\n" + response);
    setSendMessage("");
  };

  return (
    <Drawer
      title="远程调试"
      placement="right"
      width={"80%"}
      closable={false}
      onClose={onClose}
      open={visible}
      extra={<Button icon={<CloseOutlined />} onClick={onClose} />}
      maskClosable={false}
    >
      <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
        {/* 顶部设备信息 */}
        <Card size="small" style={{ marginBottom: 16 }}>
          <Space direction="vertical" style={{ width: "100%" }}>
            <div>
              <Text strong>设备名称: </Text>
              {device?.deviceName}
            </div>
            <div>
              <Text strong>设备号: </Text>
              {device?.deviceSn}
            </div>
            <div>
              <Text strong>当前状态: </Text>
              {device?.status}
            </div>
          </Space>
        </Card>

        <div style={{ display: "flex", gap: 24 }}>
          {/* 左侧控制面板 */}
          <div
            style={{ width: "20%", display: "flex", flexDirection: "column" }}
          >
            <Card
              title="连接控制"
              size="small"
              style={{ marginBottom: 16, height: "100px" }}
            >
              <div style={{ textAlign: "center", padding: 8 }}>
                <Button
                  type={isConnected ? "dashed" : "primary"}
                  danger={isConnected}
                  onClick={handleConnection}
                  style={{ width: "100%", marginBottom: 8 }}
                >
                  {isConnected ? "断开连接" : "打开连接"}
                </Button>
              </div>
            </Card>

            <Card
              title="数据格式设置"
              size="small"
              style={{ marginBottom: 16 }}
            >
              <Form form={form} layout="vertical">
                <Form.Item label="收发数据类型">
                  <Radio.Group
                    value={dataType}
                    onChange={(e) => setDataType(e.target.value)}
                    buttonStyle="solid"
                  >
                    <Radio.Button value="hex">16进制</Radio.Button>
                    <Radio.Button value="ascii">ASCII</Radio.Button>
                  </Radio.Group>
                </Form.Item>

                {/* <Form.Item label="校验方式">
                  <Select defaultValue="crc" style={{ width: "100%" }}>
                    <Option value="crc">CRC32</Option>
                    <Option value="md5">MD5</Option>
                    <Option value="none">无校验</Option>
                  </Select>
                </Form.Item> */}
              </Form>
            </Card>
          </div>

          {/* 右侧通信区域 */}
          <div
            style={{ width: "80%", display: "flex", flexDirection: "column" }}
          >
            <Card
              title="接收区"
              size="small"
              style={{ marginBottom: 16, height: "500px" }}
            >
              <Input.TextArea
                value={receiveMessage}
                readOnly
                style={{ background: "#f9f9f9", height: "440px" }}
                placeholder="接收消息将显示在这里..."
              />
            </Card>

            <Card title="发送区" size="small" style={{}}>
              <div
                style={{
                  display: "flex",
                  flexDirection: "column",
                  height: "100%",
                }}
              >
                <Input.TextArea
                  value={sendMessage}
                  onChange={(e) => setSendMessage(e.target.value)}
                  style={{ marginBottom: 8, height: "100px" }}
                  placeholder="请输入要发送的消息..."
                />
                <Button
                  type="primary"
                  icon={<SendOutlined />}
                  onClick={handleSend}
                  disabled={!isConnected}
                >
                  发送
                </Button>
              </div>
            </Card>
          </div>
        </div>

        {/* 历史记录区 */}
        <Card
          title="历史通信记录"
          size="small"
          style={{
            marginTop: 16,
            flex: "none",
            height: "300px",
          }}
        >
          <div style={{ height: "250px", overflowY: "auto", padding: 8 }}>
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                padding: "4px 0",
              }}
            >
              <Text>2025-08-20 10:30:15 → 握手请求</Text>
              <Tag color="blue">发送</Tag>
            </div>
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                padding: "4px 0",
              }}
            >
              <Text>2025-08-20 10:30:18 ← 握手确认</Text>
              <Tag color="green">接收</Tag>
            </div>
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                padding: "4px 0",
              }}
            >
              <Text>2025-08-20 10:30:22 → 状态查询</Text>
              <Tag color="blue">发送</Tag>
            </div>
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                padding: "4px 0",
              }}
            >
              <Text>2025-08-20 10:30:25 ← 状态信息(正常)</Text>
              <Tag color="green">接收</Tag>
            </div>
          </div>
        </Card>
      </div>
    </Drawer>
  );
};

export default RemoteDebugDrawer;
